<template>
	<div class="addVisiting-container">
		<van-form label-align="left" @submit="onSubmit" ref="addFollowUpForm">
			<van-cell-group>
				<van-field
					v-model="relevanceClue.title"
					is-link
					readonly
					name="picker"
					label="关联商机"
					placeholder="点击选择关联商机"
					required
					:disabled="!!followUpId"
					:rules="[{ required: true, message: '请选择关联商机' }]"
					@click="!followUpId ? showCluePicker = true : ''"
				/>
				<van-popup v-model:show="showCluePicker" position="bottom">
					<van-picker
						:columns="clueColumns"
						:columns-field-names="customFieldName"
						@confirm="onConfirmClue"
						@cancel="showCluePicker = false"
					/>
				</van-popup>
				<van-field
					v-model="followUpDate"
					is-link
					readonly
					name="datePicker"
					label="跟进日期"
					required
					disabled
					:rules="[{ required: true, message: '请选择跟进日期' }]"
				/>
				<!--				@click="showFollowUpDatePicker = true"-->
				<!--				<van-popup v-model:show="showFollowUpDatePicker" position="bottom">-->
				<!--					<van-datetime-picker-->
				<!--						type="date"-->
				<!--						:formatter="formatter"-->
				<!--						@confirm="onConfirmFollowUpDate"-->
				<!--						@cancel="showFollowUpDatePicker = false"-->
				<!--					/>-->
				<!--				</van-popup>-->
				<van-field
					v-model="userInfo.ownerUser"
					name="填写人"
					label="填写人"
					placeholder="填写人"
					disabled
				/>
				<van-field
					v-model="customerName"
					name="客户名称"
					label="客户名称"
					placeholder="客户名称"
					disabled
				/>
				<van-field
					v-model="linkman"
					name="联系人"
					label="联系人"
					placeholder="联系人"
					required
					:rules="[{ required: true, message: '请填写联系人' }]"
				/>
				<van-field
					v-model="linkmanPhone"
					name="联系电话"
					label="联系电话"
					placeholder="联系电话"
				/>
				<van-field
					v-model="deviceBrand"
					name="设备品牌"
					label="设备品牌"
					placeholder="设备品牌"
				/>
				<van-field
					v-model="deviceModel"
					name="设备型号"
					label="设备型号"
					placeholder="设备型号"
				/>
				<van-field
					v-model="format"
					name="幅面"
					label="幅面"
					placeholder="幅面"
				/>
				<van-field
					v-model="fineness"
					name="成色"
					label="成色"
					placeholder="成色"
				/>
				<van-field
					v-model="expectedQuantity"
					type="number"
					name="预下单数量"
					label="预下单数量"
					placeholder="预下单数量"
				/>
				<van-field
					v-model="expectedSignDate"
					is-link
					readonly
					name="datePicker"
					label="预下单时间"
					@click="showExpectedSignDatePicker = true"
				/>
				<van-popup v-model:show="showExpectedSignDatePicker" position="bottom">
					<van-datetime-picker
						type="date"
						:formatter="formatter"
						@confirm="onConfirmExpectedSignDate"
						@cancel="showExpectedSignDatePicker = false"
					/>
				</van-popup>
				<van-field
					v-model="customerNeeds"
					name="客户现状"
					label="客户现状"
					placeholder="客户现状"
					type="textarea"
				/>
				<van-field name="uploader" label="文件上传">
					<template #input>
						<van-uploader v-model="followUpFile" :after-read="afterRead" :before-delete="deleteFollowUpFile"  :preview-options="{closeable:'true'}" />
					</template>
				</van-field>
				<van-field
					v-model="remark"
					type="textarea"
					name="备注"
					label="备注"
					placeholder="备注"
				/>
			</van-cell-group>
			<div style="margin: 16px;">
				<van-button round block type="primary" native-type="submit">
					保存
				</van-button>
			</div>
		</van-form>
	
	</div>
</template>

<script>
import {onMounted, reactive, ref, toRefs} from "vue";
import {useRouter, useRoute} from "vue-router";
import {getBusinessFollowUp, addBusinessFollowUp, getRelevanceClue} from "@/api/businessOpportunity.js";
import {areaList} from '@/utils/area.js';
import {formatter, formatterDate} from '@/utils/index.js'
import request from "@/utils/request.js";
import {Toast} from "vant";

export default {
	setup() {
		const router = useRouter()
		const route = useRoute()
		const addFollowUpForm = ref(null)
		const state = reactive({
			userInfo: {},
			// 关联商机
			followUpId: '',
			relevanceClue: {},
			showCluePicker: false,
			clueColumns: [],
			customFieldName: {text: 'title', value: 'id'},
			followUpDate: '',
			showFollowUpDatePicker: false,
			customerName: '',
			linkman: '',
			linkmanPhone: '',
			deviceBrand: '',
			deviceModel: '',
			format: '',
			fineness: '',
			expectedQuantity: '',
			expectedSignDate: '',
			showExpectedSignDatePicker: false,
			customerNeeds: '',
			followUpFile: [],
			followUpUploadFile: [],
			remark: ''
		})
		
		onMounted(async () => {
			if (route.query.id) {
				document.title = '编辑跟进'
				state.followUpId = route.query.id
				getBusinessFollowUpDetail()
			}
			getRelevanceClueList()
			state.followUpDate = formatterDate(new Date())
			state.userInfo = JSON.parse(localStorage.getItem('userInfo'))
		})
		
		const getRelevanceClueList = () => {
			let params = {
				current: 1,
				size: 10000
			}
			getRelevanceClue(params).then(res => {
				state.clueColumns = res.records
			})
		}
		
		const getBusinessFollowUpDetail = () => {
			getBusinessFollowUp(state.followUpId).then(res => {
				console.log(",,,,,,,", res)
				state.relevanceClue.sn = res.businessSn
				state.relevanceClue.id = res.businessId
				state.relevanceClue.title = res.businessName
				state.followUpDate = res.followUpTime
				state.userInfo.ownerUser = res.ownerUser
				state.userInfo.ownerUserId = res.ownerUserId
				state.userInfo.ownerDeptId = res.ownerDeptId
				state.userInfo.ownerDeptName = res.ownerDeptName
				state.userInfo.ownerPhoneNumber = res.ownerPhoneNumber
				state.customerName = res.customerName
				state.linkman = res.contactsName
				state.linkmanPhone = res.phoneNumber
				state.deviceBrand = res.brand
				state.deviceModel = res.deviceModel
				state.format = res.format
				state.fineness = res.fineness
				state.expectedQuantity = res.expectedQuantity
				state.expectedSignDate = res.expectedSignDate
				state.customerNeeds = res.customerNeeds
				// state.followUpFile = res.enclosureList
				res.enclosureList.forEach(item => {
					state.followUpFile.push({
						url: item.value
					})
				})
				state.followUpUploadFile = res.enclosureList
				state.remark = res.remark
			})
		}
		
		const onConfirmClue = (value) => {
			console.log("///////", value)
			if (value) {
				state.relevanceClue = value;
			}
			
			if (value.followUpTime) {
				state.followUpDate = value.followUpTime
			}
			if (value.ownerUser) {
				state.userInfo.ownerUser = value.ownerUser
			}
			if (value.ownerUserId) {
				state.userInfo.ownerUserId = value.ownerUserId
			}
			if (value.ownerDeptId) {
				state.userInfo.ownerDeptId = value.ownerDeptId
			}
			if (value.ownerDeptName) {
				state.userInfo.ownerDeptName = value.ownerDeptName
			}
			if (value.ownerPhoneNumber) {
				state.userInfo.ownerPhoneNumber = value.ownerPhoneNumber
			}
			if (value.customerName) {
				state.customerName = value.customerName
			}
			if (value.contactsName) {
				state.linkman = value.contactsName
			}
			if (value.phoneNumber) {
				state.linkmanPhone = value.phoneNumber
			}
			state.showCluePicker = false;
		};
		
		const onConfirmFollowUpDate = (value) => {
			console.log("value::::", value)
			state.followUpDate = formatterDate(value);
			state.showFollowUpDatePicker = false
		}
		
		const onConfirmExpectedSignDate = (value) => {
			state.expectedSignDate = formatterDate(value);
			state.showExpectedSignDatePicker = false
		}
		
		const deleteFollowUpFile = (file, indexData) => {
			state.followUpFile.splice(indexData.index, 1)
			state.followUpUploadFile.splice(indexData.index, 1)
		}
		
		const afterRead = (file) => {
			// 此时可以自行将文件上传至服务器
			console.log(file);
			console.log("followUpFile::::", state.followUpFile)
			const formData = new FormData();
			formData.append('file', file.file);
			
			// 示例使用 axios 进行文件上传
			uploadFile(formData);
		};
		
		const uploadFile = (formData) => {
			// 使用你的上传接口地址替换以下 URL
			const url = 'web-service/oss/endpoint/put-file';
			// 这里使用 axios 作为请求示例
			request.post(url, formData, {
				headers: {
					'Content-Type': 'multipart/form-data',
				},
				onUploadProgress: progressEvent => {
					// 这里可以获取上传进度
					console.log(progressEvent);
				},
			})
				.then(response => {
					// 上传成功处理
					console.log("response::::", response);
					console.log("followUpFile::::", state.followUpFile);
					state.followUpUploadFile.push({
						label: response.originalName,
						value: response.link,
					})
				})
				.catch(error => {
					// 上传失败处理
					console.error(error);
				});
		}
		
		const onSubmit = () => {
			addFollowUpForm.value.validate().then(() => {
				let params = {
					businessSn: state.relevanceClue.sn,
					businessId: state.relevanceClue.id,
					followUpTime: state.followUpDate,
					ownerUser: state.userInfo.ownerUser,
					ownerUserId: state.userInfo.ownerUserId,
					ownerDeptId: state.userInfo.ownerDeptId,
					ownerDeptName: state.userInfo.ownerDeptName,
					ownerPhoneNumber: state.userInfo.ownerPhoneNumber,
					customerName: state.customerName,
					contactsName: state.linkman,
					phoneNumber: state.linkmanPhone,
					brand: state.deviceBrand,
					deviceModel: state.deviceModel,
					format: state.format,
					fineness: state.fineness,
					expectedQuantity: state.expectedQuantity,
					expectedSignDate: state.expectedSignDate,
					customerNeeds: state.customerNeeds,
					enclosureList: state.followUpUploadFile,
					remark: state.remark
				}
				if (state.followUpId) {
					params.id = state.followUpId
				}
				console.log("提交", params)
				addBusinessFollowUp(params).then(res => {
					console.log("res::::", res)
					Toast.success(`${state.followUpId ? '编辑' : '新增'}跟进成功！`)
					setTimeout(() => {
						router.back()
					}, 500)
				})
			})
		}
		
		return {
			areaList,
			addFollowUpForm,
			...toRefs(state),
			onSubmit,
			formatter,
			onConfirmFollowUpDate,
			onConfirmExpectedSignDate,
			onConfirmClue,
			afterRead,
			deleteFollowUpFile,
		}
	}
}

</script>

<style scoped lang="less">
.addVisiting-container {
	
	.addVisiting-save {
		display: flex;
		justify-content: flex-end;
		margin: 20px;
	}
	
}
</style>